package util

import (
	"fmt"
	"github.com/shopspring/decimal"
	"pay/pkg/ecode"
)

var decimalUnit decimal.Decimal

func init() {
	decimalUnit = decimal.New(1, 2)
}

// 元 => int分
func FromYuanToCent(f float64) int {
	return int(decimal.NewFromFloat(f).Mul(decimalUnit).IntPart())
}

// 元 => int分
func FromYuanStrToCent(f string) (cent int64, err error) {
	var d decimal.Decimal
	if d, err = decimal.NewFromString(f); err != nil {
		err = ecode.WithStack(fmt.Errorf("金额转换错误, error=%s", err.Error()))
		return
	}
	cent = d.Mul(decimalUnit).IntPart()
	return
}

// 从decimal转化为float
func FromDecimalToFloat(f decimal.Decimal) float64 {
	res, _ := f.Float64()
	return res
}

// 分 => decimal元
func FromCentToYuan(i int) float64 {
	res, _ := decimal.NewFromInt(int64(i)).DivRound(decimalUnit, 2).Float64()
	return res
}
